<?php
/*  INSERT INTO `data` VALUES ( 1, 'top', 'Tree Root', 0, 1 )  */
class Data extends Controller {
    
	function setVars()
	{
		$this->tpl['title'] = " NSDB ";
        $this->tpl['sidebar'] = FALSE;
        $this->links = 'Nested Set Tables ';
        define('URI',$this->uri->segment(1).'/'.$this->uri->segment(2));
	}
    
    function __construct()
	{
		parent::Controller();
        $this->auth->CheckTaMeR(101,100);
		$this->setVars();
        //$this->load->library('profiler');
        $this->load->model('ns_model','data');
        foreach($this->data->nsTables as $v){
            $this->links .= anchor('admin/data/index/'.$v,' =>'.$v);
        }
        if($this->uri->segment(4) !== FALSE){
        	$this->data->setTable($this->uri->segment(4));
            $this->_render_page();
        }
    }
    
	function index()
	{
        if(isset($this->data->table_name)){
        	$this->data->setTable($this->uri->segment(4));
            $this->_render_page();
        }else{
            $this->tpl['body'] = $this->links;
            $this->load->view('blank',$this->tpl);
        }
    }
    
    
    
    function insert_category()
    {
        $category_name = trim($this->input->post('categoryname'));
        $category_data = trim($this->input->post('categorydata'));
        $parentid = (int)$this->input->post('categoryid');
        $parentNode = $this->data->getNodeFromId($parentid);
        
        $fields_array = array(
        "name"=>$category_name,
        "data"=>$category_data
        );
        $this->data->appendNewChild($parentNode,$fields_array);
        
        $this->_render_page();
    }
    
    function multi_insert()
    {
        $names = trim($this->input->post('categoryname'));
        $parentid = (int)$this->input->post('categoryid');
        $parentNode = $this->data->getNodeFromId($parentid);
        $names = str_replace(', ', ',', $names);
        $names = str_replace(' ,', ',', $names);
        $namearray = explode(",", $names);
        foreach($namearray as $v){
            $fields_array = array("name"=>$v);
            $this->data->appendNewChild($parentNode,$fields_array);
        }
        
        $this->_render_page();
    }
    
    /**
     * @note	copy_category_to_table
     * @info	copy a category to a new ns table
     * @author	Dennis T. Kaplan
     * @access	public
     * @param	 
     * @return	NULL
     */	
     public function copy_category_to_table()
     {
         $this->data->table_name = 'nsd';      
         $node = $this->data->getNodeFromId('1');
         $this->data->table_name = 'ns_db_meta';
         $targetNode = $this->data->getNodeFromId('10');
         $this->data->setNodeAsFirstChild($sourceNode,$targetNode);
         
         $this->_copyTreeToTable($node, $target[$this->left_column_name]+1);
     }

    private function _copyTreeToTable($node, $targetValue)
    { 
        $sizeOfTree = $node[$this->right_column_name] - $node[$this->left_column_name] + 1;
        $this->data->_modifyNode($targetValue, $sizeOfTree);

        $newpos[$this->left_column_name] -= $sizeOfTree;
        $newpos[$this->right_column_name] -= $sizeOfTree;
  
        return $newpos;
    }

        /**
     * _modifyNode
     *
     * Adds $changeVal to all left and right values that are greater than or
     * equal to $node_int
     * 
     * @param  $node_int The value to start the shift from
     * @param  $changeVal unsigned integer value for change
     * @access private
     */
    private function _modifyNode($node_int, $changeVal)
    {
        $leftcol        =       $this->left_column_name;
        $rightcol       =       $this->right_column_name;
        $table          =       $this->data->table_name;
        
        $sql =  "UPDATE     $table " .
                "SET        $leftcol = $leftcol + $changeVal ".
                "WHERE      $leftcol >= $node_int";
        
        $this->db->query($sql);
        
        $sql =  "UPDATE     $table " .
                "SET        $rightcol = $rightcol + $changeVal ".
                "WHERE      $rightcol >= $node_int";
        
        $this->db->query($sql);
        
        return true;
    } // END: _modifyNode

     
    function move_category() 
    {
        // which category to move and where to
        $srcid = (int)$this->input->post('sourceid');
        $dstid = (int)$this->input->post('targetid');
        
        // get the corresponding node data
        $sourceNode = $this->data->getNodeFromId($srcid);
        $targetNode = $this->data->getNodeFromId($dstid);
        
        // now switch on mode to identify how to effect the move
        $mode = $this->input->post('move_mode');
        switch($mode) {
            case "firstchild":
            $method = "setNodeAsFirstChild";
            break;
            case "lastchild":
            $method = "setNodeAsLastChild";
            break;
            case "prevsibling":
            $method = "setNodeAsPrevSibling";
            break;
            case "nextsibling":
            $method = "setNodeAsNextSibling";
            break;
        }
        
        // Now to effect the move
        $this->data->$method($sourceNode,$targetNode);
        
        $this->_render_page();
        
    }
    
    
    function delete_category()
    {
        // get the categoryid of the chosen category
        $deleteid = (int) $this->input->post('deleteid');
        
        // Retrieve the node data for this category
        $targetNode = $this->data->getNodeFromId($deleteid);
        
        // perform the deletion
        $this->data->deleteNode($targetNode);
        
        
        $this->_render_page();
        
    }
    
    // Common output page 
    // Displays the current tree as a space-indented list
    // and forms for the manipulation of the tree
    function _render_page()
    {
        $data['title'] = 'Data';
        $data['head'] = '';
        $data['links'] = $this->links;
        /*        
        $start = $this->uri->segment(3,0);
        $this->load->library('pagination');
        $config['base_url']     = site_url('admin/data/'); 
        $config['total_rows']   = $this->nsm->getNumberOfChildren($this->nsm->getNodeFromId(1));
        $config['per_page']     = 10;
        $this->pagination->initialize($config);
        
        $data['sidebar'] = $this->pagination->create_links();
        */        
        $data['sidebar'] = $this->data->getTreeAsHTML();
        $data['categorySelect'] = $this->data->getAllDataSelect("categoryid");
        
        $data['moveCategorySourceSelect'] = $this->data->getAllDataSelect("sourceid");
        $data['moveCategoryTargetSelect'] = $this->data->getAllDataSelect("targetid");
        
        $data['deleteSelect'] = $this->data->getAllDataSelect("deleteid");
        
        $this->load->view('admin/data',$data);
        
    }
    
} // END: class Categories_demo
?>